package com.tuni.birthdaymoney.service.util.email.sender;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.mail.smtp.SMTPTransport;

/**
 * Sends email via SMTP<br/>
 * Encoding: windows-1251<br/>
 * Content Type: text/html
 * 
 * @author Nikita Krenev
 */
public class SMTPEmailSender extends EmailSender {

    private String hostAddress = null;
    private String hostUsername = null;
    private String hostPassword = null;

    public SMTPEmailSender(String hostAddress, String hostUsername, String hostPassword) {
        this.hostAddress = hostAddress;
        this.hostUsername = hostUsername;
        this.hostPassword = hostPassword;
    }

    @Override
    public void send(String title, String body, InternetAddress sender, InternetAddress[] directReceivers, InternetAddress[] copyReceivers)
            throws MessagingException {

        // TODO: is any real file created?
        Properties props = System.getProperties();
        props.put("mail.smtp.localhost", hostAddress);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(hostUsername, hostPassword);
            }
        });

        MimeMessage message = new MimeMessage(session);
        message.setSubject(title);
        message.setText(body);
        message.setHeader("Content-Type", "text/html;charset=windows-1251");
        message.setFrom(sender);
		message.addRecipients(Message.RecipientType.TO, directReceivers);
		message.addRecipients(Message.RecipientType.CC, copyReceivers);

		// for global hosts
		// Transport.send(message, message.getAllRecipients());

		// for local hosts
		SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
		transport.setStartTLS(true);
		transport.connect(hostAddress, hostUsername, hostPassword);
		transport.sendMessage(message, message.getAllRecipients());
    }
}